package com.ys.servers.common.mq;

import io.vertx.core.json.JsonObject;

import java.nio.ByteBuffer;

/**
 * Created by taotao on 2017/5/25.
 */
public class InternalEventData {

    private String recordAddress;

    private String apiName;

    private JsonObject paras;

    public String getRecordAddress() {
        return recordAddress;
    }

    public InternalEventData setRecordAddress(String recordAddress) {
        this.recordAddress = recordAddress;
        return this;
    }

    public String getApiName() {
        return apiName;
    }

    public InternalEventData setApiName(String apiName) {
        this.apiName = apiName;
        return this;
    }

    public JsonObject getParas() {
        return paras;
    }

    public InternalEventData setParas(JsonObject paras) {
        this.paras = paras;
        return this;
    }

    public byte[] encode() {
        byte[] a1 = this.getRecordAddress().getBytes();
        byte[] a2 = this.getApiName().getBytes();
        byte[] a3 = paras.toString().getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(24 + a1.length + a2.length + a3.length);
        buffer.putInt(a1.length);
        buffer.putInt(a2.length);
        buffer.putInt(a3.length);
        buffer.put(a1).put(a2).put(a3);
        return buffer.array();
    }

    public InternalEventData decode(byte[] rawByteDatas) {
        ByteBuffer buffer = ByteBuffer.wrap(rawByteDatas);
        int l1 = buffer.getInt();
        int l2 = buffer.getInt();
        int l3 = buffer.getInt();
        byte[] t1 = new byte[l1];
        byte[] t2 = new byte[l2];
        byte[] t3 = new byte[l3];
        buffer.get(t1);
        buffer.get(t2);
        buffer.get(t3);
        setRecordAddress(new String(t1)).setApiName(new String(t2)).setParas(new JsonObject(new String(t3)));
        return this;
    }

    public static void main(String[] args) {
        InternalEventData test = new InternalEventData().setApiName("11").setParas(new JsonObject().put("test", false).put("sdfs",23423523)).setRecordAddress("addres");
        byte[] b = test.encode();
        InternalEventData tt = new InternalEventData();
        tt.decode(b);


        String aa = new String(b);
        System.out.println(aa);

        String ab = "sss";
        byte[] c = ab.getBytes();
        String ac = new String(c);
        System.out.println(ac);

    }
}
